//
//  Oauth2ViewController.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/4/26.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
import AFNetworking

class Oauth2ViewController: UIViewController {

    let WB_AppKey = "683401259"
    let WB_AppSecret = "a40c2225afd530d1e7eee45434fd1942"
    let WB_Redirect_url = "https://www.baidu.com"
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "WB loading"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action:#selector(Oauth2ViewController.close)
)
        
        let oauthStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_AppKey)&redirect_uri=\(WB_Redirect_url)"
        
        let url = NSURL(string: oauthStr)
        let  request = NSURLRequest(URL: url!)
        /**
          有时候就算是https 请求，也不能请求成功， 是因为服务器SSL不是1.2版本
         */
        webView.loadRequest(request)
        
    
        
    
    }

    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    // 获得access_token
    private func oauthMethod(code: String) {
     
        let url = "oauth2/access_token"
        let dict: NSMutableDictionary = NSMutableDictionary()
         dict["client_id"] = WB_AppKey
         dict["client_secret"] =  WB_AppSecret
         dict["grant_type"] = "authorization_code"
         dict["code"] = code
         dict["redirect_uri"] = WB_Redirect_url
        
        NewWorkRequest.shareNewWorkRequest().POST(url, parameters: dict, success: { (_, result) in
           // print(result)
            let account = UserAccount(dict: result as! [String: AnyObject])

         
            
             account.getUserDetailInfo({ (newAct, error) in
                if newAct != nil {
                    account.saveAccount()
                    // 授权成功后，去tabbar
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchWindowRootViewController, object: false)
                }
             })
            }) { (_, error) in

        }
    }
    
    
    private lazy var webView : UIWebView = {
       let web = UIWebView(frame: UIScreen.mainScreen().bounds)
        web.delegate = self
        return web
    }()
    
}


extension Oauth2ViewController: UIWebViewDelegate{
    //Optional("https://www.baidu.com/?code=ff6d1e0fda397784c0d7d71ab4f17cc0")  授权成功
    // Optional("https://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330")

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       // print(request.URL?.absoluteString)
        
        // 把swift 中的String 转为OC的NSString
        let  urlStr: NSString = request.URL!.absoluteString
        if  urlStr.hasPrefix(WB_Redirect_url){// 用户点击授权 或者取消授权
            
//        let range = urlStr.rangeOfString("code=")
//            
//        if range.length > 0 {
//               let code = urlStr.substringFromIndex(range.location + range.length)
//                print("code++++++++++++\(code)")
//            }
//        else{
//            close()
//            }
//            return  false
            
            
            let codeStr = "code="
            if request.URL!.query!.hasPrefix(codeStr){
            let code = request.URL?.query!.substringFromIndex(codeStr.endIndex)
                oauthMethod(code!)
            }else{
                close()
            }
            return false
            
        }
        
        return true
    }
    
    
}
